package org.example.com.editor.command.workspaceCommand;

import org.example.com.editor.command.Command;
import org.example.com.editor.command.commandHistory.CommandHistoryItem;
import org.example.com.editor.command.Undoable;
import org.example.com.editor.logger.LogManager;
import org.example.com.editor.ui.ConsoleUI;
import org.example.com.editor.workspace.Workspace;

import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

public class UndoCommand implements Command {
    private final LogManager logManager;

    public UndoCommand(LogManager logManager) {
        this.logManager = logManager;
    }

    @Override
    public void execute(Workspace workspace, ConsoleUI ui) throws Exception {
        String[] args = ui.getCommandArgs();
        if (args.length != 1) {
            ui.printError("用法：undo");
            return;
        }

        try {
            CommandHistoryItem commandHistoryItem = workspace.getActiveEditor().undo();
            Undoable command = commandHistoryItem.getCommand();
            HashMap<String, Object> CommandParams = (HashMap<String, Object>) commandHistoryItem.getParams();
            command.undo(workspace.getActiveEditor(), ui,CommandParams);
        } catch (Exception e) {
            ui.printError(e.getMessage());
        }

        try {
            logManager.onCommandExecuted(workspace.getActiveFile(), args);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getName() {
        return "undo";
    }
}
